<!-- 编辑个人信息 -->
<script setup lang="ts">
import { useUserInfoStore } from '@/store/userInfo'
import avatarPlaceholder from '@/static/images/avatar_placeholder.png'
import { uploadFileAPI } from '@/apis/uploadFile'
import { updateProfileAPI } from '@/apis/updateProfile'

// import { uploadFileAPI } from '@/apis/uploadFile'
// import { updateProfileAPI } from '@/apis/uploadProfile'
// import { usegeneralConfigStore } from '@/store/generalConfig'

const router = useRouter()
const userInfoStore = useUserInfoStore()

// 表单数据
const formData = ref({
  avatar: userInfoStore.userInfo?.avatar || '',
  mobile: userInfoStore.userInfo?.mobile || '',
  nickname: userInfoStore.userInfo?.nickname || '',
})

// 校验规则
const rules = {
  avatar: [
    { required: true, message: '头像不可为空', trigger: ['blur', 'change'] },
  ],
  mobile: [
    { required: true, message: '手机号不可为空', trigger: ['blur', 'change'] },
  ],
  nickname: [
    { required: true, message: '姓名不可为空', trigger: ['blur', 'change'] },
  ],
}

// 表单组件ref
const formRef = ref<any>(null)
// 是否处于加载中状态
const loading = ref(false)
// 是否显示提交成功弹窗
const isShowSuccessModal = ref(false)

/* ------------------------------- 选择头像 START ------------------------------- */
const handleChooseAvatar = useThrottleFn(async () => {
  uni.chooseFile({
    count: 1,
    type: 'image',
    complete: (result) => {
      (result.tempFiles as File[]).forEach(async (file) => {
        const res = await uploadFileAPI({
          tempFilePath: (file as any).path,
          fileType: 'image',
        }, userInfoStore.userInfo!.token!)
        if (res.data) {
          const resData = JSON.parse(res.data)
          formData.value.avatar = resData.data.fullurl
        }
      })
    },
  })
}, 1000)
/* -------------------------------- 选择头像 END -------------------------------- */

/**
 * @description 提交表单时触发
 */
const handleSubmit = useThrottleFn(() => {
  if (userInfoStore.userInfo && userInfoStore.userInfo.token) {
    formRef.value.validate()
      .then(async () => {
        // 控制加载状态
        loading.value = true
        try {
          const res = await updateProfileAPI(
            formData.value,
            userInfoStore.userInfo!.token,
          )
          if (res.data?.code === 1) {
            userInfoStore.setUserInfo({
              ...userInfoStore.userInfo!,
              ...formData.value,
            })
            isShowSuccessModal.value = true
          }
          else { uni.showToast({ title: res.data?.msg, icon: 'none' }) }
        }
        catch (err) {
          uni.showToast({ title: '提交失败，请重试', icon: 'none' })
        }
      })
      .catch((errors: AnyObject[]) => {
        // 表单验证失败
        if (errors.length > 0)
          uni.showToast({ title: errors[0].message, icon: 'none' })
      })
  }
  else {
    uni.showToast({ title: '提交失败，请重试', icon: 'none' })
  }
})

/**
 * @description 提交成功，退出页面
 */
function handleExit() {
  router.back()
}
</script>

<template>
  <Spacer height="30" />
  <view class="mx-24rpx rounded-20rpx bg-white">
    <uv-form ref="formRef" :model="formData" :rules="rules">
      <uv-form-item prop="username" :custom-style="{ padding: 0, margin: 0 }">
        <ListCell label="昵称">
          <ListInput v-model="formData.nickname" placeholder="请输入您的姓名" />
        </ListCell>
      </uv-form-item>
      <Divider width="642" color="#E6E6E6" />
      <ListCell label="手机号">
        <ListInput v-model="formData.mobile" placeholder="请输入您的手机号" />
      </ListCell>
      <Divider width="642" color="#E6E6E6" />
      <uv-form-item prop="avatar" :custom-style="{ padding: 0, margin: 0 }">
        <button class="w-full" :style="{ padding: 0, backgroundColor: 'transparent' }" @tap="handleChooseAvatar">
          <ListCell label="头像" height="172">
            <view class="flex items-center">
              <image class="h-100rpx w-100rpx rounded-full" :src="formData.avatar || avatarPlaceholder" />
              <Spacer width="20" />
              <image class="h-24rpx w-16rpx" src="@/static/images/cheveron-right.png" />
            </view>
          </ListCell>
        </button>
      </uv-form-item>
    </uv-form>
  </view>

  <view class="fixed bottom-30rpx x-center" @tap="handleSubmit">
    <RGButton>保存修改</RGButton>
  </view>

  <uv-overlay :show="isShowSuccessModal" @tap="isShowSuccessModal = false">
    <uv-transition mode="zoom-in" :show="isShowSuccessModal">
      <view class="relative h-screen w-screen">
        <view class="absolute left-50% top-50% -translate-50%">
          <Dialog
            :show-cancel-button="false"
            title="提交成功"
            content=""
            confirm-label="确定"
            @cancel="isShowSuccessModal = false"
            @confirm="handleExit"
          >
            <template #icon>
              <image
                class="h-164rpx w-167rpx"
                src="@/static/images/checkmark_colorful.png"
              />
            </template>
          </Dialog>
        </view>
      </view>
    </uv-transition>
  </uv-overlay>
</template>

<route lang="yaml">
name: 'profileSettings'
style:
  navigationBarTitleText: '编辑个人信息'
</route>
